package top.huhuiyu.springboot.study.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.huhuiyu.springboot.study.base.BaseResult;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 胡辉煜
 */
// @ControllerAdvice表示对控制器进行增强拦截
@ControllerAdvice
@Slf4j
public class AppExceptionHandler {

  @ExceptionHandler(AppException.class)
  @ResponseBody
  public BaseResult handleException(AppException ex) {
    log.debug("应用异常信息：{}", ex.getMessage());
    return BaseResult.fail(ex.getMessage());
  }

  @ExceptionHandler(SQLException.class)
  @ResponseBody
  public BaseResult handleException(SQLException ex) {
    log.error("数据库异常", ex);
    return BaseResult.fail("数据库异常，请联系管理员或者稍后重试");
  }

  @ExceptionHandler(DataAccessException.class)
  @ResponseBody
  public BaseResult handleException(DataAccessException ex) {
    log.error("数据库操作异常", ex);
    return BaseResult.fail("数据库操作异常，请联系管理员或者稍后重试");
  }

  @ExceptionHandler(BindException.class)
  @ResponseBody
  public BaseResult handleException(BindException ex) {
    // 参数校验异常
    StringBuilder sb = new StringBuilder();
    // 获取校验的完整异常信息
    List<ObjectError> errors = ex.getAllErrors();
    errors.forEach(error -> sb.append(error.getDefaultMessage()).append(";"));
    return BaseResult.fail(sb.toString());
  }

  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseBody
  public BaseResult handleException(MethodArgumentNotValidException ex) {
    // 参数校验异常
    StringBuilder sb = new StringBuilder();
    // 获取校验的完整异常信息
    List<ObjectError> errors = ex.getAllErrors();
    errors.forEach(error -> sb.append(error.getDefaultMessage()).append(";"));
    return BaseResult.fail(sb.toString());
  }


  @ExceptionHandler(Exception.class)
  @ResponseBody
  public BaseResult handleException(Exception ex) {
    // 所有没有被明确处理的异常类型都会进入到这里,因为Exception是所有异常的父类
    log.debug("程序执行发生异常：{}", ex.getMessage());
    return BaseResult.fail(ex.getMessage());
  }

}
